package com.chenhy.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chenhy.server.mapper.AdminMapper;
import com.chenhy.server.mapper.AdminRoleMapper;
import com.chenhy.server.mapper.RoleMapper;
import com.chenhy.server.pojo.Admin;
import com.chenhy.server.pojo.AdminRole;
import com.chenhy.server.pojo.RespBean;
import com.chenhy.server.pojo.Role;
import com.chenhy.server.service.IAdminService;
import com.chenhy.server.utils.JwtTokenUtil;
import com.chenhy.server.utils.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gangan
 * @since 2022-02-13
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    // token头部信息
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    // 登录之后返回Token
    @Override
    public RespBean login(String captcha, String username, String password, HttpServletRequest request) {
        // 验证验证码
        String sessionCaptcha = (String)request.getSession().getAttribute("captcha");
        // 如果输入的验证码为空或与session中的验证码不匹配
        if (StringUtils.isEmpty(captcha) || !captcha.equalsIgnoreCase(sessionCaptcha)){
            System.out.println(captcha);
            System.out.println(sessionCaptcha);
            return RespBean.error("验证码错误，请重新输入！");
        }

        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        // 如果userDetails为空或userDetails里的密码和传入的密码不匹配
        if (userDetails == null || !passwordEncoder.matches(password,userDetails.getPassword())){
            return RespBean.error("用户名或密码不正确");
        }

        // 如果用户被禁用
        if (!userDetails.isEnabled()){
            return RespBean.error("账号被禁用，请联系管理员");
        }

        // 将登陆成功的对象打包放入SpringSecurity的上下文
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 生成Token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String, String> tokenMap = new HashMap<>();

        // 将需要返回给前端的信息封装到map
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);

        return RespBean.success("登陆成功",tokenMap);
    }

    @Override
    public Admin getAdminByUserName(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", username));
    }

    @Override
    public List<Role> getRoles(Integer id) {
        return roleMapper.getRoles(id);
    }

    @Override
    public List<Admin> getAllAdmin(String keyword) {
        return adminMapper.getAllAdmin(SecurityUtil.getCurrentAdminId(), keyword);
    }

    @Override
    @Transactional
    public RespBean updateAdminRole(Integer id, Integer[] rids) {
        adminRoleMapper.delete(new UpdateWrapper<AdminRole>().eq("admin_id",id));
        Integer result = adminRoleMapper.addAdminRole(id, rids);
        if (rids.length == result){
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");
    }

    @Override
    public RespBean updateAdminPassword(String oldPass, String pass) {
        Admin admin = SecurityUtil.getCurrentAdmin();
        System.out.println(oldPass);
        System.out.println(pass);
        System.out.println(admin.getPassword());
        System.out.println(passwordEncoder.matches(oldPass,admin.getPassword()));
        // 判断旧密码是否正确
        if (passwordEncoder.matches(oldPass,admin.getPassword())){
            admin.setPassword(passwordEncoder.encode(pass));
            int i = adminMapper.updateById(admin);
            System.out.println("进来了");
            if (i == 1){
                return RespBean.success("更新成功");
            }
        }
        return RespBean.error("更新失败");

    }

    @Override
    public RespBean updateAdminUserFace(String url) {
        Admin currentAdmin = SecurityUtil.getCurrentAdmin();
        Admin admin = adminMapper.selectById(currentAdmin.getId());
        admin.setUserFace(url);
        int i = adminMapper.updateById(admin);
        if (i==1){
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(admin, null, currentAdmin.getAuthorities()));
            return RespBean.success("更新成功", url);
        }
        return RespBean.error("更新失败");
    }
}
